<template>
  <div class="students-container">
    <!-- 卡片容器 -->
    <el-card>
      <!-- 顶部搜索和新增按钮 -->
      <div class="header">
        <!-- 搜索框 -->
        <el-input
          v-model="searchQuery"
          placeholder="搜索学号或姓名"
          prefix-icon="el-icon-search"
          @input="handleSearch"
        />
        <!-- 新增按钮 -->
        <el-button type="primary" @click="openDialog('add')"
          >新增学生</el-button
        >
        <!-- 登出按钮 -->
        <el-button type="danger" @click="logout">登出</el-button>
      </div>

      <!-- 学生表格 -->
      <el-table
        :data="filteredStudents"
        style="width: 100%"
        border
        @sort-change="handleSortChange"
      >
        <el-table-column prop="id" label="学号" width="100" sortable="custom" />
        <el-table-column prop="name" label="姓名" sortable="custom" />
        <el-table-column prop="gender" label="性别" sortable="custom" />
        <el-table-column
          prop="age"
          label="年龄"
          width="100"
          sortable="custom"
        />
        <el-table-column prop="major" label="专业" sortable="custom" />
        <el-table-column prop="class" label="班级" sortable="custom" />
        <el-table-column label="操作" width="180">
          <!-- 操作按钮 -->
          <template #default="scope">
            <el-button
              size="small"
              @click="openDialog('edit', scope.row)"
              type="primary"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              @click="deleteStudent(scope.row.id)"
              type="danger"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="block">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="totalStudents"
          :page-size="pageSize.value"
          :current-page.sync="currentPage.value"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 弹窗表单 -->
    <el-dialog
      :title="dialogMode === 'add' ? '新增学生' : '编辑学生'"
      v-model="dialogVisible"
    >
      <el-form
        :model="dialogForm"
        :rules="rules"
        label-width="80px"
        ref="formRef"
      >
        <el-form-item label="学号" prop="id">
          <!-- 新增模式下允许输入，编辑模式下设置为只读 -->
          <el-input
            v-model="dialogForm.id"
            :readonly="dialogMode === 'edit'"
            placeholder="请输入学号"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="dialogForm.name" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="dialogForm.gender" placeholder="请选择性别">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="dialogForm.age" type="number" />
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input v-model="dialogForm.major" />
        </el-form-item>
        <el-form-item label="班级" prop="class">
          <el-input v-model="dialogForm.class" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveStudent">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>
  
  <script setup>
import { reactive, ref, computed, onMounted, watch } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";

// ===================== 状态变量 =====================
const students = reactive([]); // 学生数据
const searchQuery = ref(""); // 搜索关键字
const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 每页显示条数
const totalStudents = ref(0); // 学生总数
const sortField = ref(""); // 排序字段
const sortOrder = ref(""); // 排序顺序
const dialogVisible = ref(false); // 弹窗是否可见
const dialogMode = ref("add"); // 弹窗模式（新增/编辑）
const formRef = ref(null); // 表单引用
const router = useRouter(); // 路由

// 弹窗表单初始数据
const dialogForm = reactive({
  name: "",
  gender: "",
  age: null,
  major: "",
  class: "",
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  gender: [{ required: true, message: "请选择性别", trigger: "change" }],
  age: [{ required: true, message: "请输入年龄", trigger: "blur" }],
  major: [{ required: true, message: "请输入专业", trigger: "blur" }],
  class: [{ required: true, message: "请输入班级", trigger: "blur" }],
};

// ===================== 数据获取 =====================

// 计算属性：按搜索关键字过滤学生数据
const filteredStudents = computed(() => {
  if (!searchQuery.value) return students; // 如果没有搜索关键字，返回所有数据
  return students.filter((student) => {
    return (
      student.name.includes(searchQuery.value) ||
      String(student.id).includes(searchQuery.value)
    ); // 支持学号搜索
  });
});

// 获取学生列表
const fetchStudents = async () => {
  try {
    const response = await axios.get("/api/students", {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value,
        searchQuery: searchQuery.value,
        sortField: sortField.value,
        sortOrder: sortOrder.value,
      },
    });
    if (response.data.code === 200) {
      students.splice(0, students.length, ...response.data.data.students);
      totalStudents.value = response.data.data.total;
    }
  } catch (error) {
    ElMessage.error("获取学生数据失败");
  }
};

// ===================== 事件处理 =====================
// 排序变更
const handleSortChange = ({ prop, order }) => {
  sortField.value = prop;
  sortOrder.value = order === "ascending" ? "asc" : "desc";
  fetchStudents();
};

// 搜索变更
const handleSearch = () => {
  currentPage.value = 1;
  fetchStudents();
};

// 分页变更
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
  fetchStudents();
};

// 打开弹窗
const openDialog = (mode, student = null) => {
  dialogMode.value = mode;
  dialogVisible.value = true;
  Object.assign(dialogForm, {
    id: null,
    name: "",
    gender: "",
    age: null,
    major: "",
    class: "",
  }); // 重置表单
  if (mode === "edit" && student) Object.assign(dialogForm, student); // 编辑模式填充数据
};

// 保存学生信息
const saveStudent = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogMode.value === "add") {
          await axios.post("/api/students", { ...dialogForm });
          ElMessage.success("新增成功");
        } else {
          await axios.put(`/api/students/${dialogForm.id}`, { ...dialogForm });
          ElMessage.success("编辑成功");
        }
        dialogVisible.value = false;
        fetchStudents();
      } catch (error) {
        ElMessage.error("操作失败");
      }
    }
  });
};

// 删除学生
const deleteStudent = async (id) => {
  try {
    await axios.delete(`/api/students/${id}`);
    ElMessage.success("删除成功");
    fetchStudents();
  } catch (error) {
    ElMessage.error("删除失败");
  }
};

// ===================== 监听器和初始化 =====================
watch(searchQuery, handleSearch);
onMounted(fetchStudents);

// ===================== 登出 =====================
const logout = () => {
  // 清除 localStorage 中的 token
  localStorage.removeItem("token");

  // 跳转到登录页面
  router.push("/login");
};
</script>
  
  <style scoped>
.students-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.el-input {
  width: 300px;
}

.el-pagination {
  margin-top: 20px;
  text-align: center;
}
</style>
  